﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TreadPoolCallback
{
    /// <summary>
    /// 封装Threadpool 带回调返回值
    /// </summary>
    public  class ThreadPoolCallback<T>
    {

        private  ManualResetEvent mre = new ManualResetEvent(false);


        private IAsyncResult result;


        private Func<string,T> func;


        private string str;
        /// <summary>
        /// threadpool执行 回调 并返回结果
        /// </summary>
        /// <param name="action">需异步执行方法</param>
        /// <param name="obj">action的参数</param>
        /// <param name="func1">回调函数</param>
        /// <param name="actiont">获取执行结果</param>
        public  void Start(Func<string,string> action,object obj,  Func<string,T> func1, Action<object> actiont)
        {
            try
            {
                //执行异步方法
                ThreadPool.QueueUserWorkItem((parm) =>
                {
                    //这边可以给回掉函数中的函数传参
                    str = action.Invoke(obj.ToString());
                    mre.Set();
                }, obj);

                //执行回调函数
                ThreadPool.QueueUserWorkItem((vv) =>
                {
                    mre.WaitOne();
                   
                    func = func1;
                    result = func.BeginInvoke(str + vv.ToString(), (ss) => { actiont.Invoke(ss); }, null);
                },"mm");
            }
            catch (Exception ex)
            {
            }
        }


        /// <summary>
        /// 获取返回结果
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        public  T EndExc(IAsyncResult result)
        {
           return func.EndInvoke(result);
        }

    }
}
